var protobuf = require("protobufjs");
var fs = require("fs");

const messageTypeList = fs.readdirSync("./bytes");

protobuf.load("./tree.proto", function (err, root) {
  if (err) console.log(err);
  if (!err) {
    for(let type of messageTypeList) {
      type = type.split('.')[0];
      var fileName = `./bytes/${type}.bytes`;
      var protoName = `tree.${type}`;
      var outputName = `./out/${type}.json`;
      try {
        var messageType = root.lookupType(protoName);
        let data = fs.readFileSync(fileName);
        var message = messageType.decode(data);
        fs.writeFileSync(outputName, JSON.stringify(message));
        console.log(type + " complete");
      }
      catch(e) {
        if (!e.message.startsWith('no such type')) {
          console.log(`${type}:`);
          console.log(e);
        }
      }
    }
  }
});
